// API基础配置
const API_BASE_URL = 'http://localhost:8080/api';

// --- Helper function for fetching data ---
async function fetchData(endpoint) {
    const url = `${API_BASE_URL}${endpoint}`;
    console.log(`正在请求数据: ${url}`);
        try {
            const response = await fetch(url);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            const data = await response.json();
        console.log(`获取到的数据 (${endpoint}):`, data);
            return Array.isArray(data) ? data : [];
        } catch (error) {
        console.error(`获取数据失败 (${endpoint}):`, error);
            return [];
        }
    }

// API调用工具集
const TravelAPI = {
    getAllAttractions: () => fetchData('/attractions'),
    getAttractionsByType: (type) => fetchData(`/attractions/type/${type}`),
    
    getAllFoodsV1: () => fetchData('/v1/foods'),
    getAllRestaurantsV1: () => fetchData('/v1/restaurants'),
    
    getAllCulturalActivitiesV1: () => fetchData('/v1/cultural-activities'),

    getAllTravelRoutes: () => fetchData('/travel-routes'),
    getTravelRoutesByType: (duration) => fetchData(`/travel-routes/type/${duration}`),
    
    getAllTravelGuides: () => fetchData('/travel-guides'),
    getTravelGuidesByType: (type) => fetchData(`/travel-guides/type/${type}`),
    
    getAllFAQs: () => fetchData('/faqs'),
    getFAQsByCategory: (category) => fetchData(`/faqs/category/${category}`),
    getHotFAQs: () => fetchData('/faqs/hot'),
    searchFAQs: (keyword) => fetchData(`/faqs/search?keyword=${encodeURIComponent(keyword)}`),

    getAllAccommodations: () => fetchData('/accommodations'),

    // 用户登录
    login: async function(username, password) {
        try {
            const response = await fetch(`${API_BASE_URL}/users/login`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ username, password })
            });
            return await response.json();
        } catch (error) {
            console.error('登录失败:', error);
            return { success: false, message: '登录失败，请稍后重试' };
        }
    },
    // 用户注册
    register: async function(userInfo) {
        try {
            const response = await fetch(`${API_BASE_URL}/users/register`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(userInfo)
            });
            return await response.json();
        } catch (error) {
            console.error('注册失败:', error);
            return { success: false, message: '注册失败，请稍后重试' };
        }
    },
     // 报名参加活动
     joinActivity: async function(activityId, userInfo) {
        const url = `${API_BASE_URL}/cultural-activities/${activityId}/join`;
        console.log('正在发送活动报名请求:', url, '报名信息:', userInfo);
        try {
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(userInfo)
            });
            const data = await response.json();
            console.log('活动报名响应数据:', data);
            return data;
        } catch (error) {
            console.error('活动报名失败:', error);
            return { success: false, message: '报名失败，请稍后重试' };
        }
    }
};

// 数据渲染工具集
const DataRenderer = {
    // 渲染景点详情页
    renderAttractionsDetail: function(attractions, containerId) {
        const container = document.getElementById(containerId);
        if (!container) return;
        
        const loadingPlaceholder = container.querySelector('.loading-placeholder');
        if (loadingPlaceholder) {
            loadingPlaceholder.remove();
        }

        let content = '';
        attractions.forEach(attraction => {
            content += `
                <div class="attraction-item" id="attraction-${attraction.id}">
                    <div class="attraction-image">
                        <img src="${attraction.image}" alt="${attraction.name}">
                    </div>
                    <div class="attraction-content">
                        <h3>${attraction.name}</h3>
                        <div class="attraction-meta">
                            <span><i class="fas fa-map-marker-alt"></i> ${attraction.location || '未知'}</span>
                            <span><i class="fas fa-star"></i> ${attraction.rating || '暂无评分'}</span>
                        </div>
                        <p>${attraction.description}</p>
                        <div class="attraction-info">
                            <p><strong><i class="fas fa-clock"></i> 开放时间:</strong> ${attraction.openTime || '见景区公告'}</p>
                            <p><strong><i class="fas fa-ticket-alt"></i> 门票价格:</strong> ${attraction.ticketPrice || '见景区公告'}</p>
                        </div>
                    </div>
                </div>
            `;
        });
        container.innerHTML = content;
    },
    // 渲染首页热门景点
    renderAttractions: (attractions, containerId) => {
        const container = document.getElementById(containerId);
        if (!container) {
            console.error(`Container with id ${containerId} not found.`);
            return;
        }

        const html = attractions.map(attraction => `
            <div class="feature-card">
                <div class="feature-img hover-overlay">
                    <img src="${attraction.image}" alt="${attraction.name}">
                </div>
                <div class="feature-content">
                    <h3>${attraction.name}</h3>
                    <p>${attraction.description}</p>
                    <a href="jingdian.html#${attraction.id}" class="btn">了解更多</a>
                </div>
            </div>
        `).join('');

        // 为了适应原有的三列布局，需要用一个 div 包裹起来
        container.innerHTML = `<div class="features">${html}</div>`;
    },
    // 渲染美食列表
    renderFoods: function(foods, containerId) {
        const container = document.getElementById(containerId);
        if (!container || !foods.length) return;

        const html = foods.map(food => `
            <div class="food-item">
                <div class="food-image">
                    <img src="${food.image}" alt="${food.name}">
                </div>
                <div class="food-content">
                    <h3>${food.name}</h3>
                    <p class="food-category">${food.category}</p>
                    <p>${food.description}</p>
                    <div class="food-info">
                        <span class="taste"><i class="fas fa-heart"></i> ${food.taste || '美味可口'}</span>
                        <span class="restaurant"><i class="fas fa-store"></i> ${food.restaurant || '各大餐厅'}</span>
                    </div>
                </div>
            </div>
        `).join('');

        container.innerHTML = html;
    },
    // 渲染旅游线路
    renderTravelRoutes: function(routes, containerId) {
        const container = document.getElementById(containerId);
        if (!container || !routes.length) return;

        const html = routes.map(route => `
            <div class="route-item">
                <div class="route-image">
                    <img src="${route.image}" alt="${route.name}">
                </div>
                <div class="route-content">
                    <h3>${route.name}</h3>
                    <p class="route-type">${route.duration} - ${route.theme}</p>
                    <p>${route.description}</p>
                    <div class="route-details">
                        <p><strong>行程安排：</strong>${route.schedule}</p>
                        <p><strong>交通方式：</strong>${route.transportation}</p>
                    </div>
                    <div class="route-price">
                        <span class="price">¥${route.price}</span>
                        <button class="btn btn-primary">立即预订</button>
                    </div>
                </div>
            </div>
        `).join('');

        container.innerHTML = html;
    },
    // 渲染首页最新活动
    renderHomePageActivities: (activities, containerId) => {
        const container = document.getElementById(containerId);
        if (!container) {
            console.error(`Container with id ${containerId} not found.`);
            return;
        }

        const html = activities.map(activity => {
            let day = '';
            let month = '待定';

            // 检查startDate是否为一个有效的日期字符串
            if (activity.startDate && typeof activity.startDate === 'string') {
                // 分割日期字符串以避免时区问题
                const parts = activity.startDate.split('-');
                const date = new Date(parts[0], parts[1] - 1, parts[2]);
                
                // 确保创建的日期是有效的
                if (!isNaN(date.getTime())) {
                    day = date.getDate();
                    month = (date.getMonth() + 1) + '月';
                }
            }
            
            return `
                <div class="event-item fade-in">
                    <div class="event-date">
                        <span class="day">${day || ''}</span>
                        <span class="month">${month}</span>
                    </div>
                    <div class="event-content">
                        <h3>${activity.title}</h3>
                        <div class="event-meta">
                            <span><i class="fas fa-map-marker-alt"></i> ${activity.location}</span>
                            <span><i class="fas fa-clock"></i> ${activity.displayDate}</span>
                        </div>
                        <p>${activity.mainDescription}</p>
                        <a href="wenhua.html" class="btn">查看详情</a>
                    </div>
                </div>
            `;
        }).join('');

        container.innerHTML = html;
    },
    // 显示活动报名模态框
    showJoinActivityModal: function(activityId) {
        // 这里可以实现一个简单的报名表单
        const name = prompt('请输入您的姓名：');
        const phone = prompt('请输入您的手机号：');
        
        if (name && phone) {
            TravelAPI.joinActivity(activityId, { name, phone })
                .then(result => {
                    if (result.success) {
                        alert('报名成功！我们会尽快与您联系。');
                    } else {
                        alert(result.message || '报名失败，请稍后重试。');
                    }
                });
        }
    },
    // 渲染FAQ列表
    renderFAQs: function(faqs, containerId) {
        const container = document.getElementById(containerId);
        if (!container || !faqs.length) return;

        const html = faqs.map(faq => `
            <div class="faq-item">
                <div class="faq-question">
                    <h3>${faq.question}</h3>
                    <span class="toggle-icon"><i class="fas fa-plus"></i></span>
                </div>
                <div class="faq-answer">
                    <p>${faq.answer}</p>
                </div>
            </div>
        `).join('');

        container.innerHTML = html;

        // 添加FAQ展开/收起功能
        container.querySelectorAll('.faq-question').forEach(question => {
            question.addEventListener('click', function() {
                const answer = this.nextElementSibling;
                const icon = this.querySelector('.toggle-icon i');
                
                if (answer.classList.contains('active')) {
                    answer.classList.remove('active');
                    answer.style.height = '0';
                    icon.classList.remove('fa-minus');
                    icon.classList.add('fa-plus');
                } else {
                    answer.classList.add('active');
                    answer.style.height = answer.scrollHeight + 'px';
                    icon.classList.remove('fa-plus');
                    icon.classList.add('fa-minus');
                }
            });
        });
    },

    // 新增：渲染住宿列表
    renderAccommodations: function(accommodations, containerId) {
        const container = document.getElementById(containerId);
        if (!container) return;
        
        container.innerHTML = ''; // 清空加载提示
        
        accommodations.forEach(item => {
            const accommodationCard = `
                <div class="accommodation-item">
                    <div class="accommodation-image">
                        <img src="${item.image}" alt="${item.name}">
                    </div>
                    <div class="accommodation-content">
                        <h3>${item.name}</h3>
                        <div class="accommodation-meta">
                            <span><i class="fas fa-map-marker-alt"></i> ${item.location}</span>
                            <span><i class="fas fa-star"></i> ${item.type}</span>
                        </div>
                        <p>${item.description}</p>
                        <div class="accommodation-info">
                            <p><strong>价格区间：</strong> ${item.priceRange}</p>
                            <p><strong>特色设施：</strong> ${item.facilities}</p>
                            <p><strong>周边景点：</strong> ${item.nearbyAttractions}</p>
                        </div>
                    </div>
                </div>
            `;
            container.innerHTML += accommodationCard;
        });
    },

    // 可以在这里添加更多渲染函数，例如渲染单个景点的详情等
    renderAttractionDetails: function(attraction, containerId) {
        // ... 实现渲染景点详情的逻辑 ...
    }
}; 